﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Nest;
using System;
using System.Net;
using System.Reflection.Metadata.Ecma335;

namespace Demo.Net.Elasticsearch.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ElasticSearchController : ControllerBase
    {

        private readonly ConnectionSettings settings;

        public ElasticSearchController()
        {
            settings = new ConnectionSettings(new Uri("http://192.168.31.154:9200"));
        }



        /// <summary>
        /// 创建索引
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateIndex()
        {
            var esClient = new ElasticClient(settings);
            var cresult = await esClient.Indices.CreateAsync("testindex");
            if (cresult.IsValid)
            {
                //创建别名索引--可以用别名索引来进行查询
                var a = esClient.Indices.PutAlias("testindex", "testes");
            }

            return Ok(cresult);
        }

        [HttpPost]
        public async Task<IActionResult> DelIndex()
        {
            var esClient = new ElasticClient(settings);
           var delresult= await esClient.Indices.DeleteAsync("testindex");

            return Ok(delresult);
        }

        public class TestModel
        {

 
            /// <summary>
            /// 名称
            /// </summary>
            public string StrCol1 { get; set; }

            /// <summary>
            /// 平台
            /// </summary>
            public string StrCol2 { get; set; }

            /// <summary>
            /// 其他
            /// </summary>
            public string StrCol3 { get; set; }

            /// <summary>
            /// 时间（yyyy-MM-dd）
            /// </summary>
            public DateTime DateCol1 { get; set; }

            /// <summary>
            /// 每日成功次数
            /// </summary>
            public int NumCol1 { get; set; }


            /// <summary>
            /// 每日失败次数
            /// </summary>
            public int NumCol2 { get; set; }

            /// <summary>
            /// 每日请求总数
            /// </summary>
            public int NumCol3 { get; set; }
        }

        /// <summary>
        /// 插入ES数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> IndexDocumnet()
        {
            Random r = new Random();
            var esClient = new ElasticClient(settings);
            for (int i = 0; i < 5; i++)
            {
                var name = "A" + i.ToString();
               

                var platform = "b2b";

                for (int j = 0; j < 10; j++)
                {
                    var Day = DateTime.Now.Date.AddDays(j);
                    TestModel testModel = new TestModel();
                    testModel.StrCol1 = name;
                    testModel.StrCol2 = platform;
                    testModel.StrCol3 = name + platform + i.ToString() + j.ToString();
                    testModel.DateCol1 = Day;
                    testModel.NumCol1 = r.Next(1, 10);
                    testModel.NumCol2 = r.Next(1, 10);
                    testModel.NumCol3 = testModel.NumCol1 + testModel.NumCol2;

                    var re = await esClient.IndexAsync<TestModel>(testModel, i => i.Index("testindex"));

                }
            }

            return Ok();
        }



        /// <summary>
        /// 最主要的查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Search()
        {
            var esClient = new ElasticClient(settings);


            var indexName = "testindex"; // 指定索引名称

            var searchResponse = await esClient.SearchAsync<TestModel>(s => s
                .Index(indexName)
                .From(0) // 设置起始位置
                .Size(50) // 设置每页数量

            //.Aggregations(a => a
            //    .Terms("my_terms_agg", t => t
            //        .Field(f => f.Category) // 根据Category字段进行聚合
            //        .Size(10) // 设置返回的桶数量
            //    )
            //)
            );
            return Ok(searchResponse.Documents);
        }
         /// <summary>
         /// 最完美的答案
         /// </summary>
         /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Test2()
        {
            var esClient = new ElasticClient(settings);


            var indexName = "testindex"; // 指定索引名称

            var searchResponse = esClient.Search<TestModel>(s => s
                     .Size(0) // 设置为0，因为我们不需要文档本身，只需要聚合数据
                     .Query(q => q
                         .DateRange(r => r
                             .Field(f => f.DateCol1)
                             .GreaterThanOrEquals("2023-12-09") // 设置日期过滤条件
                         )
                     )
                     .Index(indexName)
                     .Aggregations(a => a
                         .Terms("group_by_strCol1", t => t
                             .Field(f => f.StrCol1.Suffix("keyword"))
                             .Size(1 * 100) // 获取足够的桶用于分页
                             .Aggregations(aa => aa
                                 .Terms("group_by_strCol2", tt => tt
                                     .Field(ff => ff.StrCol2.Suffix("keyword"))
                                     .Aggregations(aaa => aaa
                                         .Sum("sum_numCol1", sum => sum.Field(f => f.NumCol1))
                                         .Sum("sum_numCol2", sum => sum.Field(f => f.NumCol2))
                                         .Sum("sum_numCol3", sum => sum.Field(f => f.NumCol3))
                                     )
                                 )
                             )
                         )
                     )
                 );

            // 解析聚合数据
            var buckets = searchResponse.Aggregations.Terms("group_by_strCol1").Buckets.Skip(0).Take(20);

            var resultList = new List<TestModel>();

            foreach (var bucket in buckets)
            {
                var strCol2Buckets = bucket.Terms("group_by_strCol2").Buckets;
                foreach (var subBucket in strCol2Buckets)
                {
                    var testModel = new TestModel
                    {
                        StrCol1 = bucket.Key,
                        StrCol2 = subBucket.Key,
                        NumCol1 = (int)subBucket.Sum("sum_numCol1").Value,
                        NumCol2 = (int)subBucket.Sum("sum_numCol2").Value,
                        NumCol3 = (int)subBucket.Sum("sum_numCol3").Value,
                        // DateCol1 需要额外的处理，因为它不适合在聚合中设置
                    };
                    resultList.Add(testModel);
                }
            }

          //  return resultList;

            return Ok(resultList);
        }
    }
}
